package com.xuecheng.system.interceptor;

import com.xuecheng.commons.constants.UserConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.vo.AuthInfo;
import com.xuecheng.commons.utils.AuthInfoHolder;
import com.xuecheng.commons.utils.JwtUtils;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    /*
     * 校验token
     * */

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.接收请求头token
        String token = request.getHeader("Authorization");
        //2.校验token合法性
        Boolean verifyToken = JwtUtils.verifyToken(token);
        if (verifyToken == false) {
            response.setStatus(401);//权限不足,跳转到登录页面
            throw new BusinessException(ErrorCode.NOTTOKEN);
        }
        //3.解析token
        AuthInfo authInfo = JwtUtils.getInfoFromToken(token);
        //4.判断redis是否过期
        if (!redisTemplate.hasKey(UserConstants.USER_ID + authInfo.getUid())) {
            response.setStatus(401);
            throw new BusinessException(ErrorCode.NOTTOKEN);
        }
        //5.判断小于1小时,续期
        Long expire = redisTemplate.getExpire(UserConstants.USER_ID + authInfo.getUid(), TimeUnit.HOURS);
        if (expire < 1) {
            redisTemplate.expire(UserConstants.USER_ID+authInfo.getUid(),3,TimeUnit.HOURS);
        }
        //6.存入threadLocal
        AuthInfoHolder.setAuthInfo(authInfo);
        //7.放行
        return true;
    }
    //清理token

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AuthInfoHolder.remove();
    }
}
